package com.maila.simplerecord.activity;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.maila.simplerecord.R;
import com.maila.simplerecord.adapter.ImgAdapter;
import com.maila.simplerecord.adapter.ProgressAdapter;
import com.maila.simplerecord.data.ProjectProgressdata;
import com.maila.simplerecord.data.Projectdata;
import com.maila.simplerecord.view.CustomDatePickerDialog;
import com.maila.simplerecord.view.EditProgressPop;
import com.maila.simplerecord.view.HorizontalListView;
import com.maila.simplerecord.view.NoScrollListView;
import com.zhy.autolayout.AutoLayoutActivity;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

import static com.maila.simplerecord.R.id.tv_edit;

/**
 * Created by Administrator on 2017/6/2.
 */

public class SubjectDetailActivity extends AutoLayoutActivity {

    @BindView(R.id.white_return_iv)
    ImageView whiteReturnIv;
    @BindView(R.id.white_message_iv)
    TextView whiteMessageIv;
    @BindView(tv_edit)
    TextView tvEdit;
    @BindView(R.id.arl_art)
    AutoRelativeLayout arlArt;
    @BindView(R.id.tv_projectname)
    TextView tvProjectname;
    @BindView(R.id.tv_project_address)
    TextView tvProjectAddress;
    @BindView(R.id.tv_project_data)
    TextView tvProjectData;
    @BindView(R.id.clint_name)
    TextView clintName;
    @BindView(R.id.clint_phone)
    TextView clintPhone;
    @BindView(R.id.ll_show_info)
    AutoLinearLayout llShowInfo;
    @BindView(R.id.ed_projectname)
    EditText edProjectname;
    @BindView(R.id.ed_projectaddress)
    EditText edProjectaddress;
    @BindView(R.id.tv_add_progress)
    TextView tvAddProgress;
    @BindView(R.id.tv_project_time)
    TextView tvProjectTime;
    @BindView(R.id.ed_clint_name)
    EditText edClintName;
    @BindView(R.id.ed_clint_phone)
    EditText edClintPhone;
    @BindView(R.id.ll_edit_info)
    AutoLinearLayout llEditInfo;
    @BindView(R.id.nlv_project_progress)
    NoScrollListView nlvProjectProgress;
    @BindView(R.id.ed_note)
    EditText edNote;
    @BindView(R.id.iv_add_img)
    ImageView ivAddImg;
    @BindView(R.id.hlv_imgs)
    HorizontalListView hlvImgs;
    @BindView(R.id.btn_save)
    TextView btnSave;
    Projectdata projectdata;
    Context context;
    Calendar cal;
    ImgAdapter imgadapter;
    String startime = "";
    List<String> imgsdata=new ArrayList<>();
    int opt = 0;//0是编辑状态 1是非编辑状态
    int pid;
    ProgressAdapter pgadapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subjectdetail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        context = this;
        pid = getIntent().getIntExtra("pid", 0);
        opt = getIntent().getIntExtra("opt", 0);
        imgadapter = new ImgAdapter(context);
        pgadapter=new ProgressAdapter(context);
        nlvProjectProgress.setAdapter(pgadapter);
        hlvImgs.setAdapter(imgadapter);
        if (pid == 0) {
            projectdata = new Projectdata();
            if(Projectdata.getcount()>0){
                projectdata.pid = Projectdata.getlastpid() + 1;
            }else {
                projectdata.pid=1;
            }
        } else {
            projectdata = Projectdata.getRandom(pid);
            showdata();
        }
        updatastatus();
        nlvProjectProgress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(opt==1){
                    EditProgressPop progressPop=new EditProgressPop(SubjectDetailActivity.this,pgadapter.getItem(position));
                    progressPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER,0,0);
                }
            }
        });
        hlvImgs.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if(opt==1){
                    showMessageOK("确定要移除该图片?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            imgadapter.remove(position);
                            imgadapter.notifyDataSetChanged();
                            String imgs = "";
                            for (int i = 0; i < imgadapter.getImgs().size(); i++
                                    ) {
                                if (i ==  imgadapter.getImgs().size() - 1) {
                                    imgs = imgs + imgadapter.getImgs().get(i);
                                } else {
                                    imgs = imgs + imgadapter.getImgs().get(i) + ",";
                                }
                            }
                            projectdata.img_paths = imgs;
                            projectdata.save();
                        }
                    });
                    return true;
                }

            return false;
            }
        });
    }


    private void showMessageOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .create()
                .show();
    }
    private void showdata() {
        TestSet(tvProjectname, projectdata.project_name);
        TestSet(edProjectname, projectdata.project_name);
        TestSet(tvProjectAddress, projectdata.address);
        TestSet(edProjectaddress, projectdata.address);
        if (projectdata.start_time != null && projectdata.end_time != null) {
            tvProjectTime.setText(projectdata.start_time + "--" + projectdata.end_time);
            tvProjectData.setText(projectdata.start_time + "--" + projectdata.end_time);
        }
        if(projectdata.img_paths!=null){
            imgadapter.getImgs().clear();
            imgadapter.notifyDataSetChanged();
            String[] imgs=projectdata.img_paths.split(",");
            for(int i=0;i<imgs.length;i++){
                imgsdata.add(imgs[i]);
            }
            imgadapter.setImgs(imgsdata);
        }
        getprogresslist();
        TestSet(clintName, projectdata.client_name);
        TestSet(clintPhone, projectdata.client_phone);
        TestSet(edNote, projectdata.note);
        TestSet(edClintName, projectdata.client_name);
        TestSet(edClintPhone, projectdata.client_phone);
    }

    private void getprogresslist() {
        List<ProjectProgressdata> mdatas=ProjectProgressdata.getAll(projectdata.pid);
        if(mdatas!=null&&mdatas.size()>0){
            pgadapter.setImgs(mdatas);
        }
    }

    private void TestSet(TextView clintPhone, String client_phone) {
        if (client_phone != null) {
            clintPhone.setText(client_phone);
        }

    }
    private void TestSet(EditText clintPhone, String client_phone) {
        if (client_phone != null) {
            clintPhone.setText(client_phone);
        }
    }

    @OnClick({tv_edit, R.id.white_return_iv, R.id.clint_phone, R.id.tv_project_time, R.id.iv_add_img, R.id.btn_save, R.id.tv_add_progress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.white_return_iv:
                finish();
                break;
            case R.id.clint_phone:
                if (projectdata.client_phone != null&&isPhoneNumber(projectdata.client_phone)) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + projectdata.client_phone);
                    intent.setData(data);
                    context.startActivity(intent);
                }
                break;
            case R.id.tv_project_time:
                showTimeDialog("开始时间", 1);
                break;
            case R.id.iv_add_img:
                showgalery();
                break;
            case tv_edit:
                opt = 1;
                updatastatus();
                break;
            case R.id.tv_add_progress:
                ProjectProgressdata projectProgressdata=new ProjectProgressdata();
                projectProgressdata.pid=projectdata.pid;
                projectProgressdata.subid=ProjectProgressdata.getlastsubid()+1;
                projectProgressdata.save();
                EditProgressPop progressPop=new EditProgressPop(this,projectProgressdata);
                progressPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER,0,0);
                break;
            case R.id.btn_save:
                if (opt == 0) {
                    if (projectdata.top == 1) {
                        projectdata.top = 0;
                    } else {
                        projectdata.top = 1;
                    }
                    projectdata.save();
                    finish();
                } else {
                    if(!"".equals(edProjectname.getText().toString())&&!"".equals(edProjectaddress.getText().toString())&&!"".equals(tvProjectTime.getText().toString())){
                        if(!"".equals(edClintPhone.getText().toString())&&!isPhoneNumber(edClintPhone.getText().toString())){
                            Toast.makeText(context,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        opt = 0;
                        savedata();
                        updatastatus();
                        showdata();
                    }else {
                        Toast.makeText(context,"请完善项目信息,名称地址时间",Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    private void showgalery() {

        int hasReadStargePermission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int hasCameraPermission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED || hasReadStargePermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                    101);
        } else {
            PhotoPickerIntent intent = new PhotoPickerIntent(context);
            intent.setPhotoCount(9);
            intent.setShowCamera(true);
            startActivityForResult(intent, 303);
        }
    }

    public  boolean isPhoneNumber(String phoneNumber) {
        Pattern pattern = Pattern.compile("^1[3|4|5|7|8][0-9]{9}$");
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void mainEvenTHread(String event) {
        if("progress".equals(event)){
            getprogresslist();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        Intent intent = new Intent();

//        更改头像
        if (resultCode == Activity.RESULT_OK && requestCode == 303) {
            if (data != null) {
                final List<String> photos =
                        data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                String imgs = "";
                imgadapter.addallImgs(photos);
                for (int i = 0; i < imgadapter.getImgs().size(); i++
                        ) {
                    if (i ==  imgadapter.getImgs().size() - 1) {
                        imgs = imgs + imgadapter.getImgs().get(i);
                    } else {
                        imgs = imgs + imgadapter.getImgs().get(i) + ",";
                    }
                }
                projectdata.setImg_paths(imgs);
                projectdata.save();
            }
        }
    }

    private void savedata() {
        projectdata.client_phone=edClintPhone.getText().toString();
        projectdata.client_name=edClintName.getText().toString();
        projectdata.project_name=edProjectname.getText().toString();
        projectdata.address=edProjectaddress.getText().toString();
        projectdata.note=edNote.getText().toString();
        projectdata.save();
    }

    /**
     * 更改状态
     */
    private void updatastatus() {
        if (opt == 0) {
            llEditInfo.setVisibility(View.GONE);
            llShowInfo.setVisibility(View.VISIBLE);
            ivAddImg.setVisibility(View.GONE);
            tvAddProgress.setVisibility(View.GONE);
            if (projectdata.top == 1) {
                btnSave.setText("取消首页显示");
            } else {
                btnSave.setText("发送到首页");
            }
            edNote.setEnabled(false);
            tvEdit.setVisibility(View.VISIBLE);
        } else {
            tvEdit.setVisibility(View.GONE);
            llEditInfo.setVisibility(View.VISIBLE);
            llShowInfo.setVisibility(View.GONE);
            ivAddImg.setVisibility(View.VISIBLE);
            tvAddProgress.setVisibility(View.VISIBLE);
            edNote.setEnabled(true);
            btnSave.setText("保存");
        }
    }


    void showTimeDialog(String hint, final int opt) {
        hideSoftInput();
        cal = Calendar.getInstance();
        String sDate = "";
        if (opt == 1) {
            if (projectdata.start_time != null) {
                sDate = projectdata.start_time;
            }
        } else {
            if (projectdata.end_time != null) {
                sDate = projectdata.end_time;
            }
        }
        if (!sDate.trim().isEmpty()) {
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                Date date1 = format.parse(sDate);
                cal.setTime(date1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //获取年月日时分秒的信息
        int year = cal.get(Calendar.YEAR);
        //month从0开始计算(一月month = 0)
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);

        //设置标题
        setTitle(year + "-" + month + "-" + day + " " + hour + ":" + minute);
        //日历选择器的对话框形式
        new CustomDatePickerDialog(this, R.style.Theme_Alert_Dialog, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//                        setTitle(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                if (opt == 1) {
                    projectdata.start_time = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
                    startime = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
                    showTimeDialog("结束时间", 0);
                } else {
                    projectdata.end_time = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
                    tvProjectTime.setText(startime + " - " + year + "." + (monthOfYear + 1) + "." + dayOfMonth);
                }
            }
        }, year, cal.get(Calendar.MONTH), day, hint).show();

    }

    //    隐藏系统软键盘
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }
}
